package com.yan.club.sys.control;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yan.club.result.Result;
import com.yan.club.sys.dto.SysDictDataDto;
import com.yan.club.sys.model.SysDictData;
import com.yan.club.sys.service.SysDictDataService;
import com.yan.club.sys.service.SysDictTypeService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.yan.club.auth.utils.SecurityUtil.getUser;

/**
 * @author 彦
 * @since 2024/2/7 15:15
 */
@RestController
@RequestMapping("/sys/dict/data")
public class SysDictDataController {

    @Resource
    private SysDictDataService dictDataService;

    @Resource
    private SysDictTypeService dictTypeService;

    /**
     * 查询全部数据
     *
     * @param dictData
     * @return
     */
    @PreAuthorize("@check.hasAuthority('system:dict:list')")
    @GetMapping("/list")
    public Result<PageInfo<SysDictData>> list(SysDictDataDto dictData) {
        PageHelper.startPage(dictData.getPageNum(), dictData.getPageSize(), true);
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);

        return Result.success(new PageInfo<>(list));
    }

    /**
     * 查询字典数据详细
     */
    @PreAuthorize("@check.hasAuthority('system:dict:query')")
    @GetMapping(value = "/{dictCode}")
    public Result<SysDictData> getInfo(@PathVariable Long dictCode) {
        return Result.success(dictDataService.selectDictDataById(dictCode));
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public Result<List<SysDictData>> dictType(@PathVariable String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (ObjectUtils.isEmpty(data)) {
            data = new ArrayList<>();
        }
        return Result.success(data);
    }

    /**
     * 新增字典类型
     */
    @PreAuthorize("@check.hasAuthority('system:dict:add')")
    @PostMapping
    public Result<String> add(@Validated @RequestBody SysDictData dict) {
        dict.setCreateBy(getUser().getUserName());
        return dictDataService.insertDictData(dict);
    }

    /**
     * 修改保存字典类型
     */
    @PreAuthorize("@check.hasAuthority('system:dict:edit')")
    @PutMapping
    public Result<String> edit(@Validated @RequestBody SysDictData dict) {
        dict.setUpdateBy(getUser().getUserName());
        return dictDataService.updateDictData(dict);
    }


    /**
     * 删除字典类型
     */
    @PreAuthorize("@check.hasAuthority('system:dict:remove')")
    @DeleteMapping("/{dictCodes}")
    public Result<String> remove(@PathVariable Long[] dictCodes) {
        dictDataService.deleteDictDataByIds(dictCodes);
        return Result.success();
    }
}
